package com.cpe.service.file;

import javax.annotation.Resource;

import org.javatuples.Pair;
import org.springframework.stereotype.Service;

import com.qiniu.common.QiniuException;
import com.qiniu.data.QiniuEnv;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.util.file.FilenameUtil;
import com.wechat.api.WechatAPI;

@Service
public class FileUploadService {
	@Resource
	private QiniuEnv qiniuEnv;

	@Resource
	private UploadManager uploadManager;

	@Resource
	private WechatAPI wechatAPI;

	/**
	 * 上传文件到七牛服务器上
	 * 
	 * @param data
	 * @return
	 */
	public String upload(String media_id) throws Exception {
		Pair<byte[], String> pair = wechatAPI.download(media_id);
		String path = qiniuEnv.getDir() + FilenameUtil.withUUID(pair.getValue1());
		Response response = uploadManager.put(pair.getValue0(), path, qiniuEnv.getUptoken());
		if (response.isOK()) {
			return qiniuEnv.getHost() + "/" + path;
		}
		throw new QiniuException(response);
	}
}
